import React, {useEffect, useRef} from 'react';
import * as echarts from 'echarts';
import styled from 'styled-components';

type Props = {
  option: echarts.EChartsOption;
  chartHeight?: string;
  id?: string;
  clickAction?: (name: string) => void;
}
const Container = styled.div<{chartHeight: string | undefined }>`
  background: white;
  margin:10px;
  border-radius: 16px;
  height: ${props => props.chartHeight || "250px"};
`;
const Echarts: React.FC<Props> = (props) => {
  const {option, clickAction, chartHeight} = props;
  const container = useRef<HTMLDivElement>(null);
  const chart = useRef<echarts.ECharts | null>(null);

  const handleResize = () => {
    chart.current?.resize()
  }

  useEffect(() => {
    if (container.current === null) return;
    chart.current = echarts.init(container.current);
    window.addEventListener('resize', handleResize)
    return () => {
      chart.current?.dispose();
      window.removeEventListener('resize', handleResize)
    };
  }, []);

  useEffect(() => {
    chart.current?.setOption(option);
  }, [option]);

  useEffect(() => {
    if(!clickAction || !chart.current) return
    chart.current.off('click') // 防止触发两次点击事件
    chart.current.getZr().on('click', (params: any) => {
      const pointInPixel = [params.offsetX, params.offsetY]
      if (!chart.current || !chart.current.containPixel({gridIndex: 0}, pointInPixel)) return
      const pointInGrid = chart.current.convertFromPixel({seriesIndex:0}, pointInPixel)
      const xIndex = Number(pointInGrid[0]) + 1
      const option = chart.current.getOption()
      // @ts-ignore
      const month = option.dataset[0].source[xIndex][0]
      const monthStartDate = month.replaceAll('.', '-') + '-01';
      clickAction(monthStartDate);
    });
  }, [clickAction]);


  return (
    <Container ref={container} chartHeight={chartHeight}/>
  );
};

export {Echarts};